package com.ybkj.daijia;

import com.alibaba.fastjson.JSONObject;
import com.ybkj.daijia.serverUtils.SettingUtils;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * @author zhyu
 * @date 2020/1/7 15:03
 * restTemplate的工具
 */
@Component
public class RestTemplateUtils {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SettingUtils settingUtils;

    /**
     * 创建新的带appkey的map, 或者为存在的map添加appkey
     * 注意新的map的大小只有1
     * @param params
     */
    public void addAppKey(Map<String, Object> params) {
        if (params == null) {
            params = new HashMap<>(1);
        }
        params.put("appKey", settingUtils.get().getSecKey());
    }
    /**
     * get请求, 返回的是String, 只需要带参数的map传进去就好了,
     * @param params
     * @param url
     * @return
     */
    public String getRequestForString(Map<String, Object> params, String url) {
        StringBuilder sb = new StringBuilder(url);
        if (params == null) {
            params = new HashMap(0);
        }
        if (params.size() > 0) {
            sb.append("?");
            for (Entry<String, Object> entry : params.entrySet()) {
                if (sb.charAt(sb.length() - 1) == '?') {
                    sb.append(entry.getKey()).append("=").append(entry.getValue());
                } else {
                    sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
                }
            }
        }
        ResponseEntity<String> forEntity = restTemplate.getForEntity(sb.toString(), String.class, params);
        return forEntity.getBody();
    }

    public JSONObject getRequestForJsonObject(Map<String, Object> params, String url) {
        String requestForString = getRequestForString(params, url);
        if (requestForString != null) {
            return JSONObject.parseObject(requestForString);
        }
        return null;
    }

    public T getRequestForJsonObject(Map<String, Object> params, String url, Class<T> clasz) {
        String requestForString = getRequestForString(params, url);
        if (requestForString != null) {
            return JSONObject.parseObject(requestForString, clasz);
        }
        return null;
    }
}
